import { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import type { ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import semver from "semver";
import type { MirrorWebsiteFile } from "@common/spider-types.ts";
import { getMirrorOptions, type MirrorNames } from "@/modules/dev-env/mirror/data.ts";

/**
 * Maven Daemon下载源
 */
export class MvndMirror extends BaseEnvMirror {
  constructor(name: MirrorNames) {
    super(getMirrorOptions(name, name === "apache" ? "/maven/mvnd/" : "/apache/maven/mvnd/"));
  }

  protected getDownloadList0(files: MirrorWebsiteFile[]): ToolInstallVersionItem[] {
    // 过滤掉 1.0-m6/7/8的版本
    const versions = files.filter(it => /^\d+\..*$/.test(it.name) && !/m\d+$/.test(it.name));
    versions.sort((a, b) => semver.compare(b.name, a.name));
    return versions.map(it => {
      return {
        id: `mvnd-${it.name}`,
        name: getMvndFileName(it.name),
        version: it.name,
        url: getMvndDownloadPath(this.url, it.name),
        date: it.date,
        size: it.size,
      };
    });
  }
}

function getMvndFilePlatform() {
  return native.process.platform === "win32" ? "windows" : native.process.platform;
}

function getMvndFileArch() {
  if (native.process.platform === "darwin" && native.process.arch === "arm64") return "aarch64";
  return "amd64";
}

function getMvndDownloadPath(mirror: string, version: string) {
  return `${mirror}${version}/maven-mvnd-${version}-${getMvndFilePlatform()}-${getMvndFileArch()}.zip`;
}

function getMvndFileName(version: string, ext = "zip") {
  return `maven-mvnd-${version}-${getMvndFilePlatform()}-${getMvndFileArch()}.${ext}`;
}
